<?php
/**
 * @package RSS STOK
 * @copyright Авторские права (C) 2009 www.yar-it.com. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * RSS STOK! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
 */

// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );

if (!($acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'all' ) | $acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'com_contact' ))) {
	mosRedirect( 'index2.php', _NOT_AUTH );
}

// Get the right language if it exists
if (file_exists($mosConfig_absolute_path.'/administrator/components/com_rss_stok/languages/'.$mosConfig_lang.'_admin.php')) {
	include_once($mosConfig_absolute_path.'/administrator/components/com_rss_stok/languages/'.$mosConfig_lang.'_admin.php');
} else {
	include_once($mosConfig_absolute_path.'/administrator/components/com_rss_stok/languages/russian_admin.php');
}

require_once( $mainframe->getPath( 'admin_html' ) );
require_once( $mainframe->getPath( 'class' ) );

$id = intval(mosGetParam( $_REQUEST, 'id', 0 ));
$cid = josGetArrayInts('cid');

if(is_array($cid) && $cid[0]!=0){
	$id =$cid[0];
}

switch ($task) {

	case 'save':
		rssStok::save( $option );
		break;

 	case 'cancel':
		rssStok::cancel($option, $task, $id );
		break;

	case 'apply':
		$id = rssStok::save( $option, $task, 0 );
	case 'new':
	case 'edit':
	case 'editA':
		rssStok::edit($option, $task, $id);
		break;

	case 'del':
		rssStok::del( $option, $section, $task, $cid );
		break;

	case 'publish':
		rssStok::changePublished( $cid, 1, $option, $task );
		break;

	case 'unpublish':
		rssStok::changePublished( $cid, 0, $option, $task );
		break;
	
	case 'list':
	default:
		rssStok::show( $option,'list' );
		break;
}

class rssStok {
	/**
	* 
	* @param $option 
	*/
	function changePublished( $cid=null, $state=0, $option, $task ){
		global $my;

		$database	= &database::getInstance();

		if (count( $cid ) < 1) {
			$action = $state == 1 ? _PUBLISHED : _NOT_PUBLISHED;
			echo "<script> alert('"._RSSST_SELITEM." $action'); window.history.go(-1);</script>\n";
			exit;
		}
		$search = mosGetParam( $_REQUEST, 'search', '' );
		
		$total = count ( $cid );
		$cids = implode( ',', $cid );

		$query = "UPDATE #__rss_stok"
		. "\n SET published = $state"
		. "\n WHERE id IN ( $cids ) AND ( checked_out = 0 OR (checked_out = $my->id ) )";
		$database->setQuery( $query );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
			exit();
		}

		if (count( $cid ) == 1) {
			$row = new rssStokData( $database );
			$row->checkin( $cid[0] );
		}

		if ( $state == "1" ) {
			$msg = $total . _RSSST_ITEMSP;
		} else if ( $state == "0" ) {
			$msg = $total . _RSSST_ITEMSUP;
		}

		mosRedirect( 'index2.php?option='. $option . '&amp;task=list&amp;search='. $search . '&mosmsg='. $msg );
	}	
	// ---------------------------------------------------------------
	/**
	* 
	* @param $option 
	*/
	function show( $option, $task ) {
		global $mainframe, $mosConfig_list_limit;
		require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );

		$database	= &database::getInstance();

		$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
		$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );

		$search = mosGetParam( $_REQUEST, 'search', '' );
		
		$filter = "";
		if ($search) {
			$filter .= "WHERE name like '%$search%'";
		}

		// get the total number of records
		$database->setQuery( "SELECT count(*) FROM #__rss_stok $filter");
		
		$total = $database->loadResult();
		
		$pageNav = new mosPageNav( $total, $limitstart, $limit );
		
		$query = "SELECT * "
		. "\n  FROM  #__rss_stok "
		. "\n $filter "
		. "\n ORDER BY name "
		. "\n LIMIT $pageNav->limitstart,$pageNav->limit"
		;
		$database->setQuery( $query );
		$rows = $database->loadObjectList();
	
		if ($database->getErrorNum()) {
			echo $database->stderr();
			return false;
		}
		HtmlRdRss::show( $option,  $task, $rows, $pageNav, $search );
	}
	// ---------------------------------------------------------------
	/**
	* edit a records
	* @param string The current GET/POST option
	*/
	function edit( $option, $task, $id ) {
		global $mosConfig_absolute_path;

		$database	= &database::getInstance();

		$row = new rssStokData( $database );
		$row->load( $id );
	
		// fail if checked out not by 'me'
		if ($row->checked_out && $row->checked_out <> $my->id) {
			mosRedirect( 'index2.php?option='. $option, _RSSST_TI . $row->name . _RSSST_EAA );
		}
		$lookup 			= '';
		if ($id) {
			$catids=$row->catids;
			if ( $catids ) {
				$query = "SELECT c.id AS `value`, c.section AS `id`, CONCAT_WS( ' / ', s.title, c.title) AS `text`"
				. "\n FROM #__sections AS s"
				. "\n INNER JOIN #__categories AS c ON c.section = s.id"
				. "\n WHERE s.scope = 'content'"
				. "\n AND c.id IN ( $catids )"
				. "\n ORDER BY s.name,c.name"
				;
				$database->setQuery( $query );
				$lookup = $database->loadObjectList();
			}

		}else{
			$row->published = 1;
		}
		// build the html select list for category
		$category[] = mosHTML::makeOption( '', _RSSST_ALLCATS );
		$query = "SELECT c.id AS `value`, c.section AS `id`, CONCAT_WS( ' / ', s.title, c.title) AS `text`"
		. "\n FROM #__sections AS s"
		. "\n INNER JOIN #__categories AS c ON c.section = s.id"
		. "\n WHERE s.scope = 'content'"
		. "\n ORDER BY s.name,c.name";
		$database->setQuery( $query );
		$category = array_merge( $category, $database->loadObjectList() );
		$category = mosHTML::selectList( $category, 'catid[]', 'class="inputbox" size="10" multiple="multiple"', 'value', 'text', $lookup );
		$lists['catids'] = $category;
		if ($id == '1') {
			$params =& new mosParameters( $row->params, $mosConfig_absolute_path.'/administrator/components/com_rss_stok/rss_xf_config.xml', 'component' );
		} else {
			$params =& new mosParameters( $row->params, $mosConfig_absolute_path.'/administrator/components/com_rss_stok/rss_x_config.xml', 'component' );
		}	
		HtmlRdRss::edit($option, $task, $id, $row, $params, $lists);
	}
	// ---------------------------------------------------------------
	/**
	* 
	* @param $option 
	*/
	function del($option, $section, $task, $cid) {
		$database	= &database::getInstance();
		
		foreach ($cid as $elm) {
			if ($elm != '1') {
				$row = new rssStokData( $database );
				$row->load( $elm );
				$row->delete();
			} else {
				$noway = 1;	
			}		
		}	
		if ($noway) {
			mosRedirect( "index2.php?option=$option&amp;task=list", _RSSST_FCNBD );
		} else {	
			mosRedirect( "index2.php?option=$option&amp;task=list" );
		}	
	}
	// ---------------------------------------------------------------
	/**
	* 
	* @param $option 
	*/
	function cancel($option, $task, $id ) {
		$database	= &database::getInstance();
		if ($id) {
			$row = new rssStokData( $database );
			$row->load( $id );
			$row->checkin();	
		}
		
		mosRedirect( "index2.php?option=$option&amp;task=list" );
	}
	// ---------------------------------------------------------------
	/**
	* 
	* @param $option 
	*/
	function save($option, $section, $task, $redirect=1) {
		global $mainframe,$my;
		$database	= &database::getInstance();

		$row = new rssStokData( $database );
		if (!$row->bind( $_POST )) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}

		$params = mosGetParam( $_POST, 'params', '' );
		if (is_array( $params )) {
			$txt = array();
			foreach ( $params as $k=>$v) {
				$txt[] = "$k=$v";
			}
			$row->params = implode( "\n", $txt );
		}
		$catids	= mosGetParam( $_POST, 'catid', array() );
		$row->catids	= implode( ',', $catids );
		
		$isNew = ($row->id < 1);
		if ($isNew) {
			
			$row->created			= $row->created ? $row->created : date( "Y-m-d H:i:s" );
			$row->created_by 		= $row->created_by ? $row->created_by : $my->id;
			$row->modified 			= date( "Y-m-d H:i:s" );
			$row->modified_by 		= $my->id;
		} else {
			$row->modified 			= date( "Y-m-d H:i:s" );
			$row->modified_by 		= $my->id;
			$row->checkin();
		}

		if (!$row->store()) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}	
	
		$msg = $row->name . _RSSST_SCSA;
		if ($redirect) {
			mosRedirect( "index2.php?option=$option&amp;task=list", $msg );
		} else {
			return $row->id;
		}
	}
}